package xin.yangshuai.springsecurity03.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.yangshuai.common01.entity.BaseResult;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * UserDetailsController
 *
 * @author shuai
 * @date 2025/8/28
 */
@RestController
@RequestMapping("userDetails")
public class UserDetailsController {

    @Autowired
    private UserDetailsManager userDetailsManager;

    @GetMapping("add")
    public BaseResult<Integer> add() {

        String encodingId = "bcrypt";
        Map<String, PasswordEncoder> encoders = new HashMap();
        encoders.put(encodingId, new BCryptPasswordEncoder());
        encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
        // ...

        encodingId = "MD5";
        PasswordEncoder encoder = new DelegatingPasswordEncoder(encodingId, encoders);

        int i = new Random().nextInt(100);

        UserDetails userDetails1 = User.builder().passwordEncoder(encoder::encode).username("test" + i).password("123456").authorities("USER_LIST").build();
        userDetailsManager.createUser(userDetails1);

        BaseResult<Integer> result = new BaseResult<>();
        result.setCode("200");
        result.setData(1);
        return result;
    }
}
